const GatherDevice = require("../models/gatherDeviceModel"); // 确保路径正确
const Device = require("../models/DeviceModel");
// 添加新设备
const addGatherDevice = async (data) => {
  const { deviceName } = data; // 从请求体中获取设备名称和账号数组
  console.log("添加新设备", JSON.stringify(data), deviceName);
  let res = {
    code: 0,
    status: "success",
    message: "添加设备成功",
    data: null,
  };

  try {
    // const newDevice = new Device({
    //   deviceName: deviceName,
    //   accountStatus: "上线",
    // }); // 创建新的 GatherDevice 实例
    // const savedDevice = await newDevice.save(); // 保存到数据库
    const updatedDevice = await Device.findOneAndUpdate(
      { deviceName: deviceName }, // 查询条件
      { accountStatus: "上线" }, // 更新内容
      { new: true, upsert: true } // 返回更新后的文档，若不存在则插入
    );
    // console.log("设备保存成功:", updatedDevice);
    res = { data: updatedDevice };
  } catch (error) {
    let errorMessage = error.message;
    console.log("设备保存失败:", errorMessage);
    if (error.name === "MongoError" && error.code === 11000) {
      errorMessage = "已存在相同设备名称";
    }
    res = {
      code: 1,
      status: "error",
      message: "添加设备失败",
      data: null,
    };
  }

  return res;
};

module.exports = { addGatherDevice };
